// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const { carNumber, entryTime, expectedLeaveTime } = event

  try {
    // 获取用户信息
    const { data: users } = await db.collection('users')
      .where({
        _openid: OPENID
      })
      .get()

    if (users.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }

    const user = users[0]

    // 创建申请记录
    const result = await db.collection('applications').add({
      data: {
        applicantId: user._id,
        applicantName: user.name,
        roomNumber: user.roomNumber,
        phone: user.phone,
        carNumber,
        entryTime: new Date(entryTime),
        expectedLeaveTime: new Date(expectedLeaveTime),
        status: 'pending',
        createTime: db.serverDate()
      }
    })

    return {
      success: true,
      message: '申请提交成功'
    }

  } catch (error) {
    console.error(error)
    return {
      success: false,
      message: '提交失败，请重试'
    }
  }
} 